/**
 * 
 */
package com.istart.tika.output;

import java.io.IOException;
import java.io.InputStream;

import org.apache.tika.exception.TikaException;
import org.apache.tika.metadata.Metadata;
import org.apache.tika.parser.AutoDetectParser;
import org.apache.tika.sax.BodyContentHandler;
import org.apache.tika.sax.ToXMLContentHandler;
import org.apache.tika.sax.XHTMLContentHandler;
import org.apache.tika.sax.xpath.Matcher;
import org.apache.tika.sax.xpath.MatchingContentHandler;
import org.apache.tika.sax.xpath.XPathParser;
import org.junit.Test;
import org.xml.sax.ContentHandler;
import org.xml.sax.SAXException;

/**
 * @author 谢进军
 *
 */
public class TikeOutput {
	private final static String filepath = "/com/istart/tika/content/tika.txt";
	
	private final static String filename = "tika.txt";
	
	private final static String xx = "/cdbpdc(sql版)产品介绍_20151126.docx";
	
	@Test public void parseToPlainText() throws IOException, SAXException, TikaException{
		BodyContentHandler handler = new BodyContentHandler();
		 
	    AutoDetectParser parser = new AutoDetectParser();
	    Metadata metadata = new Metadata();
	    InputStream stream = TikeOutput.class.getResourceAsStream(filepath);
	    parser.parse(stream, handler, metadata);
	    System.out.println(handler.toString());
	}
	//--------------------to xml
	/**
	 * 
	 * @throws IOException
	 * @throws SAXException
	 * @throws TikaException
	 */
	@Test public void parseToHTML() throws IOException, SAXException, TikaException{
		ContentHandler handler = new ToXMLContentHandler();
		AutoDetectParser parser = new AutoDetectParser();
		Metadata metadata = new Metadata();
		InputStream stream = TikeOutput.class.getResourceAsStream(filepath);
		parser.parse(stream, handler, metadata);
		System.out.println(handler.toString());
	}
	
	@Test public void parseToHTMLWithoutHead() throws IOException, SAXException, TikaException{
		ContentHandler handler = new BodyContentHandler(new ToXMLContentHandler());
		AutoDetectParser parser = new AutoDetectParser();
		Metadata metadata = new Metadata();
		InputStream stream = TikeOutput.class.getResourceAsStream(filepath);
		parser.parse(stream, handler, metadata);
		System.out.println(handler.toString());
	}
	
	//----------------------------
	@Test public void parseOnePartToHTML() throws IOException, SAXException, TikaException {
	    // Only get things under html -> body -> div (class=header)
	    XPathParser xhtmlParser = new XPathParser("xhtml", XHTMLContentHandler.XHTML);
	    Matcher divContentMatcher = xhtmlParser.parse("/xhtml:html/xhtml:body/xhtml:div/descendant::node()");
	    ContentHandler handler = new MatchingContentHandler(new ToXMLContentHandler(), divContentMatcher);
	 
	    AutoDetectParser parser = new AutoDetectParser();
	    Metadata metadata = new Metadata();
	    try (InputStream stream = TikeOutput.class.getResourceAsStream( filepath)) {
	        parser.parse(stream, handler, metadata);
	        System.out.println(handler.toString());
	    }
	}
}
